<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="queryParams.address" placeholder="请输入地址" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="联系人" prop="contacts">
        <el-input v-model="queryParams.contacts" placeholder="请输入联系人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="联系人电话号码" prop="phone" label-width="120px">
        <el-input v-model="queryParams.phone" placeholder="请输入联系人电话号码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="daterangeCreateTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd()" v-hasPermi="['camera:community:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-if="refreshTable" v-loading="loading" :data="communityList" row-key="id" :default-expand-all="isExpandAll" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <!-- <el-table-column label="父级uuid" prop="parentId" />
        <el-table-column label="祖级列表" align="center" prop="ancestors" /> -->
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="联系人" align="center" prop="contacts" />
      <el-table-column label="联系人电话号码" align="center" prop="phone" />
      <el-table-column label="楼栋层数" align="center" prop="floorNumber" />
      <el-table-column label="时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['camera:community:edit']">修改</el-button>
          <el-button size="mini" v-if="scope.row.address !== null" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)" v-hasPermi="['camera:community:add']">
            新增
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['camera:community:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改小区楼栋信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父级uuid" prop="parentId">
          <treeselect v-model="form.parentId" :options="communityOptions" :normalizer="normalizer" placeholder="请选择父级uuid" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="地址" prop="address" v-if="showAddress">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="联系人" prop="contacts">
          <el-input v-model="form.contacts" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系人电话号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系人电话号码" oninput="value=value.replace(/[^\d]/g,'')" maxLength='11' />
        </el-form-item>
        <el-form-item label="楼栋层数" prop="floorNumber" v-if="showFloorNumber">
          <el-input v-model="form.floorNumber" placeholder="请输入楼栋层数" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script>
import { listCommunity, getCommunity, delCommunity, addCommunity, updateCommunity } from "@/api/camera/community";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Community",
  components: {
    Treeselect
  },
  data () {
    return {
      showFloorNumber: true, // 是否显示楼栋层数
      showAddress: true, // 是否显示地址
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 小区楼栋信息表格数据
      communityList: [],
      // 小区楼栋信息树选项
      communityOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 删除标志时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        id: null,
        name: null,
        address: null,
        contacts: null,
        phone: null,
        createTime: null,
        del: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "父级uuid不能为空", trigger: "blur" }
        ],
        ancestors: [
          { required: true, message: "祖级列表不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        address: [
          { required: true, message: "地址不能为空", trigger: "blur" }
        ],
        contacts: [
          { required: true, message: "联系人不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "联系人电话号码不能为空", trigger: "blur" },
          { pattern: /^1[34578]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        floorNumber: [
          { required: true, message: "楼栋层数不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        del: [
          { required: true, message: "删除标志不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created () {
    this.getList();
  },
  methods: {
    /** 查询小区楼栋信息列表 */
    getList () {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listCommunity(this.queryParams).then(response => {
        const filteredData = response.data.filter(item => item.parentId !== null && item.parentId !== undefined);
        this.communityList = this.handleTree(filteredData, "id", "parentId");
        this.loading = false;
      });
    },
    /** 转换小区楼栋信息数据结构 */
    normalizer (node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    /** 查询小区楼栋信息下拉树结构 */
    getTreeselect () {
      listCommunity().then(response => {
        this.communityOptions = this.handleTree(response.data, "id", "parentId");
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        id: null,
        parentId: null,
        ancestors: null,
        name: null,
        address: null,
        contacts: null,
        phone: null,
        floorNumber: null,
        createTime: null,
        updateTime: null,
        del: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd (row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {//
        this.form.parentId = row.id;
        this.showFloorNumber = row.parentId != null
        console.log(this.showFloorNumber, 1111111111111);
        this.showAddress = row.parentId == null
        console.log(this.showAddress, 1111111111111);
      } else {
        this.form.parentId = null;
        this.showFloorNumber = false; // 默认隐藏楼栋层数
        this.showAddress = true; // 默认隐藏地址
      }
      this.open = true;
      this.title = "添加小区楼栋信息";
    },
    /** 展开/折叠操作 */
    toggleExpandAll () {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.id;
        this.showFloorNumber = !row.id.startsWith("0");
        this.showAddress = row.id.startsWith("0");
      } else {
        this.form.parentId = 0;
        this.showFloorNumber = true;
        this.showAddress = true;
      }
      getCommunity(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改小区楼栋信息";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCommunity(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCommunity(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      this.$modal.confirm('是否确认删除小区楼栋信息编号为"' + row.id + '"的数据项？').then(function () {
        return delCommunity(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    // 判断是否为第四级节点的方法
    isFourthLevel (row) {
      return row.parentId !== 0 && this.findParent(row.parentId).parentId !== 0;
    },
    // 辅助方法，根据 parentId 查找父节点
    findParent (parentId) {
      return this.deptList.find(item => item.deptId === parentId);
    },
  }
};
  </script>
  